package org.penguin.study.bk.base.json;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;

/**
 * double 精确到小数点后两位
 *
 * @author chengyinghua
 */
public class CustomerDoubleSerialize extends JsonSerializer<Double> {

    private DecimalFormat df = new DecimalFormat("0.00");

    @Override
    public void serialize(Double arg0, JsonGenerator arg1, SerializerProvider arg2) throws IOException {
        if (arg0 != null) {
            BigDecimal bigDecimal = new BigDecimal(String.valueOf(arg0));
            df.setRoundingMode(RoundingMode.HALF_UP);
            // 四舍五入。需要将数据转成bigDecimal, 否则会存在经度丢失问题
            String format = df.format(bigDecimal);
            double aDouble = Double.parseDouble(format);

            //返回数字格式
            arg1.writeNumber(aDouble);
        }
    }
}